package com.nmgsr.ptmsapp.fragment;

import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SnapHelper;

import com.google.gson.Gson;
import com.nmgsr.beans.entity.GridItem;
import com.nmgsr.beans.entity.PtmsUser;
import com.nmgsr.beans.requestdao.PageReq;
import com.nmgsr.beans.responsedao.PtmsBorrowRecordRes;
import com.nmgsr.beans.responsedao.PtmsUserInfoRes;
import com.nmgsr.beans.responsedao.SysRoleRes;
import com.nmgsr.beans.service.Api;
import com.nmgsr.nettools.base.BaseFragment;
import com.nmgsr.nettools.net.config.NetManager;
import com.nmgsr.nettools.net.retrofit.BaseResponse;
import com.nmgsr.nettools.net.retrofit.HttpHelper;
import com.nmgsr.nettools.net.retrofit.HttpResponseObserver;
import com.nmgsr.nettools.net.retrofit.HttpUtil;
import com.nmgsr.nettools.net.retrofit.PagedResult;
import com.nmgsr.ptmsapp.R;
import com.nmgsr.ptmsapp.activity.ListActivity;
import com.nmgsr.ptmsapp.activity.ListPtmsBorrowRecordActivity;
import com.nmgsr.ptmsapp.activity.ListPtmsToolActivity;
import com.nmgsr.ptmsapp.activity.ListPtmsVideoCaptureActivity;
import com.nmgsr.ptmsapp.activity.ListPtmsWarnScrapActivity;
import com.nmgsr.ptmsapp.activity.ListPtmsWarnTestActivity;
import com.nmgsr.ptmsapp.activity.MyMapEchartsActivity;
import com.nmgsr.ptmsapp.activity.QRCodeScannerActivity;
import com.nmgsr.ptmsapp.adapter.GridAdapter;
import com.nmgsr.ptmsapp.adapter.HomeListAdapter;
import com.nmgsr.ptmsapp.adapter.ListAdapter;
import com.nmgsr.ptmsapp.adapter.ListPtmsBorrowRecordAdapter;
import com.nmgsr.ptmsapp.config.PreferencesManager;
import com.nmgsr.ptmsapp.view.MyDividerItemDecoration;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends BaseFragment implements View.OnClickListener{
    Banner banner;
    private GridView gridView;

    private ListPtmsBorrowRecordAdapter adapter;
    private String token;
    private int page = 1;
    private SmartRefreshLayout refreshLayout;

    private TextView textView_loginName,tv_companyName;

    @Override
    public void onClick(View v) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.home_fragment;
    }

    @Override
    public void initView() {
        iv_status_bar.setVisibility(View.VISIBLE);
        fl_actionbar.setVisibility(View.GONE);
        mContext = getActivity();
        textView_loginName = rootView.findViewById(R.id.textView_loginName);
        tv_companyName = rootView.findViewById(R.id.tv_companyName);
        banner = rootView.findViewById(R.id.banner);
        initBanner();
        // 初始化网格数据
        List<GridItem> gridItems = new ArrayList<>();
        gridItems.add(new GridItem(R.drawable.tool, "台账记录"));
        gridItems.add(new GridItem(R.drawable.photo, "抓拍记录"));
        gridItems.add(new GridItem(R.drawable.bad, "报废提醒"));
        gridItems.add(new GridItem(R.drawable.exam, "试验提醒"));
        gridItems.add(new GridItem(R.drawable.record, "出入记录"));

        // 设置适配器
        gridView = rootView.findViewById(R.id.grid_view);
        gridView.setAdapter(new GridAdapter(mContext, gridItems));

        // 设置点击事件
        gridView.setOnItemClickListener((parent, view, position, id) -> {
            // 处理点击事件
            handleGridItemClick(position);
        });

        RecyclerView recyclerView = rootView.findViewById(R.id.recyclerView);
        // 设置只显示一个 item
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return true; // 允许垂直滚动
            }
        };
        recyclerView.setLayoutManager(layoutManager);

        SnapHelper snapHelper = new LinearSnapHelper();
        snapHelper.attachToRecyclerView(recyclerView);

        MyDividerItemDecoration divider = new MyDividerItemDecoration(mContext, MyDividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(mContext, R.drawable.custom_divider));
        recyclerView.addItemDecoration(divider);

        adapter = new ListPtmsBorrowRecordAdapter();
        recyclerView.setAdapter(adapter);
        token = PreferencesManager.getToken(mContext);
        refreshLayout = rootView.findViewById(R.id.refresh_layout);
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            page = 1;
            getData();
        });
        getData();
        getUserInfo();
    }
    public void initBanner() {
        List<Integer> list = new ArrayList<>();
        list.add(R.drawable.banner1);
        list.add(R.drawable.banner2);
        banner.setAdapter(new BannerImageAdapter<Integer>(list) {
            @Override
            public void onBindView(BannerImageHolder holder, Integer data, int position, int size) {
                Picasso.get().load(data).into(holder.imageView);
            }
        });
        banner.setIndicator(new CircleIndicator(getActivity()));
        banner.setIndicatorRadius(300);
    }
    private void handleGridItemClick(int position) {
        Intent intent;
        // 根据位置执行不同操作
        switch (position) {
            case 0:
                // 工器具台账记录
                intent = new Intent(mContext, ListPtmsToolActivity.class);
                startActivity(intent);
                break;
            case 1:
                // 抓拍记录
                intent = new Intent(mContext, ListPtmsVideoCaptureActivity.class);
                startActivity(intent);
                break;
            case 2:
                // 报废提醒
                intent = new Intent(mContext, ListPtmsWarnScrapActivity.class);
                startActivity(intent);
                break;
            case 3:
                // 试验提醒
                intent = new Intent(mContext, ListPtmsWarnTestActivity.class);
                startActivity(intent);
                break;
            case 4:
                // 出入库记录
                intent = new Intent(mContext, ListPtmsBorrowRecordActivity.class);
                startActivity(intent);
                break;
            // ... 其他case
        }
    }
    private void getData() {
        PageReq pageReq = new PageReq();
        pageReq.setPage(1);
        pageReq.setPageSize(5);
        NetManager.getInstance().setAuthorizationToken(token);
        HttpHelper.getInstance()
                .getService(Api.class)
                .getPtmsBorrowRecordList(pageReq)
                .compose(HttpUtil.defaultSchedulers())
                .compose(bindToLifecycle())
                .subscribe(new HttpResponseObserver<BaseResponse<PagedResult<PtmsBorrowRecordRes>>>() {

                    @Override
                    protected void onSuccess(BaseResponse<PagedResult<PtmsBorrowRecordRes>> response) {
                        if (response.isSuccess()) {
                            List<PtmsBorrowRecordRes> roleList = response.getResult().getItems();
                            if (page == 1) {
                                if (roleList != null && !roleList.isEmpty()) {
                                    // 更新UI数据
                                    adapter.setList(roleList);
                                    refreshLayout.finishRefresh();
                                } else {
                                    QMUIEmptyView qmuiEmptyView = new QMUIEmptyView(mContext);
                                    qmuiEmptyView.show(false, "暂无数据", null, getString(R.string.emptyView_mode_desc_retry),
                                            v -> refreshLayout.autoRefresh());
                                    adapter.setEmptyView(qmuiEmptyView);
                                    refreshLayout.finishRefresh();
                                }
                            }
                        } else {
                            Toast.makeText(mContext, "错误：" + response.getMessage(), Toast.LENGTH_SHORT).show();
                            refreshLayout.finishRefresh(false);
                        }
                    }

                    @Override
                    protected void handleError(Throwable e) {
                    }
                });
    }

    private void getUserInfo() {
        NetManager.getInstance().setAuthorizationToken(token);
        HttpHelper.getInstance()
                .getService(Api.class)
                .getUserInfo()
                .compose(HttpUtil.defaultSchedulers())
                .compose(bindToLifecycle())
                .subscribe(new HttpResponseObserver<BaseResponse<PtmsUserInfoRes>>() {

                    @Override
                    protected void onSuccess(BaseResponse<PtmsUserInfoRes> response) {
                        if (response.isSuccess()) {
                            Log.e("UserInfo", "response: " + new Gson().toJson(response));
                            PtmsUserInfoRes userInfoRes=response.getResult();
                            PtmsUser user=new PtmsUser();
                            user.setAccount(userInfoRes.getAccount());
                            user.setNickName(userInfoRes.getNickName());
                            user.setSignature(userInfoRes.getSignature());
                            PreferencesManager.saveUserInfo(mContext,user);
                            textView_loginName.setText(userInfoRes.getNickName());
                            tv_companyName.setText(userInfoRes.getPhone());

                        } else {
                            Toast.makeText(mContext, "错误：" + response.getMessage(), Toast.LENGTH_SHORT).show();
                            refreshLayout.finishRefresh(false);
                        }
                    }

                    @Override
                    protected void handleError(Throwable e) {
                    }
                });
    }
}
